package com.cxs.plan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.plan.VO.PayVO;
import com.cxs.plan.domain.entity.PayCard;
import com.cxs.plan.domain.entity.UserWithBill;
import com.cxs.plan.mapper.UserWithBillMapper;
import com.cxs.plan.service.PayCardService;
import com.cxs.plan.mapper.PayCardMapper;
import com.cxs.plan.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
* @author Administrator
* @description 针对表【pay_card(支付卡包)】的数据库操作Service实现
* @createDate 2024-04-02 16:57:25
*/
@Service
public class PayCardServiceImpl extends ServiceImpl<PayCardMapper, PayCard>
    implements PayCardService{

    @Autowired
    private PayCardMapper payCardMapper;

    @Override
    public List<PayCard> getPayCardList() {
        LambdaQueryWrapper<PayCard> wrapper = new LambdaQueryWrapper<>();
        wrapper.select().eq(PayCard::getUserId, BaseContext.getCurrentId());
        return payCardMapper.selectList(wrapper);
    }

    @Transactional
    @Override
    public void addPayCard(PayCard payCard) {
        payCard.setUserId(BaseContext.getCurrentId());
        payCardMapper.insert(payCard);
    }

    @Override
    public PayCard getPayCardInfo(Long id) {
        return payCardMapper.selectById(id);
    }

    @Override
    public Object getPayCardDetail(Integer id) {
        payCardMapper.selectPayCardDetail(id);
        return null;
    }

    @Override
    public List<PayVO> getPayCardRecord(Integer id) {
        List<PayVO> payVOS = payCardMapper.selectPayCardRecord(id);
        AtomicReference<BigDecimal> minusPrice = new AtomicReference<>(new BigDecimal(0));
        payVOS.forEach(i -> {
            if(minusPrice.get().equals(new BigDecimal(0))) minusPrice.set(new BigDecimal(i.getSurplus()));
            minusPrice.set(minusPrice.get().add(new BigDecimal(i.getPrice())));
            BigDecimal surplus = minusPrice.get(); // 计算 surplus
            // 计算剩余预算比例
            BigDecimal surplusRateDecimal = surplus.divide(new BigDecimal(i.getSurplus()), 4, BigDecimal.ROUND_HALF_UP);
            // 将剩余预算比例转换为百分比
            i.setSurplusRate(surplusRateDecimal.multiply(new BigDecimal(100)).doubleValue());
            i.setSurplus(minusPrice.get().toString());
        });
        return payVOS;
    }
}




